<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="活动名称" prop="promotionName">
        <el-input
          v-model="queryParams.promotionName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="couponActivityType">
        <el-select
          v-model="queryParams.couponActivityType"
          placeholder="活动类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.mall_coupon_activity_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动范围" prop="activityScope">
        <el-select
          v-model="queryParams.activityScope"
          placeholder="活动类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.mall_coupon_activity_scope"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.mall_promotion_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall-manager:coupon-activity:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="promotionName" />
      <el-table-column label="活动类型" align="center" prop="couponActivityType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_coupon_activity_type" :value="scope.row.couponActivityType"/>
        </template>
      </el-table-column>
      <el-table-column label="活动范围" align="center" prop="activityScope" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_coupon_activity_scope" :value="scope.row.activityScope"/>
        </template>
      </el-table-column>
      <el-table-column label="领取频率" align="center" prop="couponFrequencyEnum">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_coupon_activity_frequency" :value="scope.row.couponFrequencyEnum"/>
        </template>
      </el-table-column>

      <el-table-column label="活动时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope" >
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span> </br>
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="promotionStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_promotion_state" :value="scope.row.promotionStatus"/>
        </template>

      </el-table-column>
      <el-table-column label="启用" align="center" prop="isEnable" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
        </template>

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">


        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item  v-hasPermi="['mall-manager:coupon-activity:query']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-viewt"
                  @click="handleView(scope.row)"
                >查看</el-button>
              </el-dropdown-item>
              <el-dropdown-item  v-if="scope.row.isEnable == 0" v-hasPermi="['mall-manager:coupon-activity:edit']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                >修改</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isEnable == 0"  v-hasPermi="['mall-manager:coupon-activity:edit']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-check"
                  @click="handleEnable(scope.row)"
                >启用</el-button>
              </el-dropdown-item>
              <el-dropdown-item  v-hasPermi="['mall-manager:coupon-activity:edit']" v-if="scope.row.isEnable == 1 && (scope.row.promotionStatus === 'START' || scope.row.promotionStatus === 'NEW')">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-close"
                  @click="handleClose(scope.row)"
                >关闭</el-button>
              </el-dropdown-item>
              <el-dropdown-item command="a"  v-if="scope.row.isEnable == 0"   v-hasPermi="['mall-manager:coupon-activity:remove']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商城优惠券活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="65%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="promotionName">
              <el-input v-model="form.promotionName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动时间" >
              <el-date-picker
                v-model="formDateRange"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="活动类型" prop="couponActivityType">
              <el-radio-group v-model="form.couponActivityType" >
                <el-radio-button label="REGISTERED" >新人发券</el-radio-button>
                <el-radio-button label="SPECIFY" >精确发券</el-radio-button>
                <el-radio-button label="INVITE_NEW" >邀新赠券</el-radio-button>
                <el-radio-button label="AUTO_COUPON" >自动赠券</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领取频率" prop="price" v-if="form.couponActivityType == 'AUTO_COUPON'">
              <el-radio-group v-model="form.couponFrequencyEnum" size="small">
                <el-radio-button label="DAY" >每日一次</el-radio-button>
                <el-radio-button label="WEEK" >每周一次</el-radio-button>
                <el-radio-button label="MONTH" >每月一次</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="活动范围" prop="activityScope" v-if="form.couponActivityType === 'SPECIFY'">
              <el-radio-group v-model="form.activityScope">
                <el-radio-button label="ALL" >全部会员</el-radio-button>
                <el-radio-button label="DESIGNATED" >指定会员</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>



        <el-card class="box-card" v-if="form.couponActivityType === 'SPECIFY' &&form.activityScope === 'DESIGNATED'">
          <div slot="header" class="clearfix">
            <span>选择会员</span>
          </div>
          <div class="form-item-view">
            <el-button type="primary"  @click="handMemberChoose">选择会员</el-button>

            <el-table  :data="selectMemberList" border style="margin-top: 10px">
              <el-table-column label="用户名称" align="center" prop="nickName" />
              <el-table-column label="手机号" align="center" prop="mobile" />
              <el-table-column label="最后登录时间" align="center" prop="lastLoginDate" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="delMember(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </div>
        </el-card>



        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>配置优惠券</span>
          </div>
          <div class="form-item-view">
            <el-button type="primary"   @click="handCouponChoose">选择优惠券</el-button>
            <el-table  :data="selectCouponList" border style="margin-top: 10px">
              <el-table-column label="优惠券名称" align="center" prop="couponName" />
              <el-table-column label="品类描述" align="center" prop="scopeType" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mall_coupon_scope_type" :value="scope.row.scopeType"/>
                </template>
              </el-table-column>
              <el-table-column label="面额/折扣" align="center" >
                <template slot-scope="scope">
                  <span v-if="scope.row.couponType == 'PRICE'">{{ scope.row.price }} / 元</span>
                  <span v-if="scope.row.couponType == 'POINT'">{{ scope.row.couponDiscount }} / 折</span>
                </template>
              </el-table-column>
              <el-table-column label="赠送数量" align="center" >
                <template slot-scope="scope">
                  <el-input
                    type="number"
                    placeholder="请输入赠送数量"
                    v-model="scope.row.num"
                    min="1"
                    max="100"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="delCoupon(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </div>
        </el-card>






      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  优惠券选择   -->
    <el-dialog title="选择优惠券" :visible.sync="couponopen" v-if="couponopen" width="80%" >
      <coupon-choose  :selectedWay="selectCouponList" @selectedCouponData="selectedCoupon"></coupon-choose>
    </el-dialog>

    <!--  会员选择   -->
    <el-dialog title="选择会员" :visible.sync="memberopen" v-if="memberopen" width="80%" >
      <member-choose  :selectedWay="selectMemberList" @selectedMemberData="selectedMember"></member-choose>
    </el-dialog>

    <!--  优惠券查看   -->
    <el-dialog title="查看" :visible.sync="viewopen" v-if="viewopen" width="65%" append-to-body>
      <coupon-view :activityId="id"></coupon-view>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCouponActivity,
  getCouponActivity,
  delCouponActivity,
  addCouponActivity,
  updateCouponActivity,
  enableCouponActivity,
  closeCoupon
} from "@/api/mall/promotion/coupon-activity";
import CouponChoose from '@/views/mall/promotion/coupon/choose.vue'
import MemberChoose from '@/views/uac/member/choose.vue'
import CouponView from './view'
export default {
  name: "CouponActivity",
  dicts: ['sys_is_enable','mall_coupon_activity_type','mall_coupon_activity_scope','mall_coupon_activity_frequency','mall_coupon_scope_type','mall_promotion_state'],
  components: {
    CouponView,CouponChoose,MemberChoose
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewopen: false,
      couponopen: false,
      memberopen: false,
      // 日期范围
      dateRange: [],
      formDateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        endTime: null,
        promotionName: null,
        activityScope: null,
        couponActivityType: null,
        startTime: null,
        couponName: null,
        couponType: null,
        getType: null,
        state: null,
        scopeType: null,
      },
      // 表单参数
      form: {},
      scopeIdGoods: [],
      promotionGoodsList: [],
      selectedGoods: [],
      rangeTimeType: 1,
      catProps: {
        value: 'id',
        label: 'name'
      },
      // 表单校验
      rules: {
        promotionName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 20, message: '活动名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        couponActivityType: [
          { required: true, message: "请选择活动类型", trigger: "blur" },
        ],
        couponType: [
          { required: true, message: "请选择优惠券类型", trigger: "blur" },
        ],
        getType: [
          { required: true, message: "请选择优惠券领取方式", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入活动范围描述", trigger: "blur" },
        ],
        consumeThreshold: [
          { required: true, message: "请输入消费门槛", trigger: "blur" },
        ],
        scopeType: [
          { required: true, message: "请选择使用范围", trigger: "blur" },
        ],
        rangeTime: [{ required: true, message: "请选择优惠券有效期" ,trigger: "blur"}],
      },
      id: null,
      selectCouponList: [], //选择的优惠券列表
      selectMemberList: [], //选择的会员列表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商城优惠券列表 */
    getList() {
      this.loading = true;
      if (this.dateRange.length > 0){
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      }
      listCouponActivity(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        endTime: null,
        promotionName: null,
        storeId: null,
        storeName: null,
        startTime: null,
        consumeThreshold: null,
        couponDiscount: null,
        couponLimitNum: 1,
        couponName: null,
        price: null,
        publishNum: -1,
        receivedNum: null,
        scopeId: null,
        scopeType: null,
        storeCommission: null,
        couponFrequencyEnum: null,
        activityScope: 'ALL'
      };
      this.resetForm("form");
      this.formDateRange = []
      this.selectCouponList = []
      this.selectMemberList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商城优惠券活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCouponActivity(id).then(response => {
        this.form = response.data.couponActivity;
        this.formDateRange[0] = this.form.startTime
        this.formDateRange[1] = this.form.endTime
        this.selectCouponList = response.data.items;
        this.selectMemberList = response.data.members;
        this.open = true;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewopen = true;
      this.id = row.id
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formDateRange.length < 1){
            this.$modal.msgError("请选择活动时间");
            return
          }else{
            this.form.startTime = this.formDateRange[0]
            this.form.endTime = this.formDateRange[1]
          }

          if (!this.selectCouponList || this.selectCouponList.length == 0){
            this.$modal.msgError("请选择要赠送的优惠券");
            return;
          }

          if (this.form.couponActivityType === 'SPECIFY' && this.form.activityScope === 'DESIGNATED'){
             this.form.members = this.selectMemberList.map(obj => obj.id);
          }
          this.form.items = this.selectCouponList



          if (this.form.id != null) {
            updateCouponActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCouponActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商城优惠券编号为"' + ids + '"的数据项？').then(function() {
        return delCouponActivity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const id = row.id ;
      this.$modal.confirm('是否确认启用？').then(function() {
        return enableCouponActivity(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 关闭按钮操作 */
    handleClose(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认关闭？').then(function() {
        return closeCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },


    delCoupon(index) {
      // 删除优惠券
      this.selectCouponList.splice(index, 1);
    },
    delMember(index) {
      // 删除会员
      this.selectMemberList.splice(index, 1);
    },
    handCouponChoose(){
      this.couponopen = true
    },
    handMemberChoose(){
      this.memberopen = true
    },
    /**
     * 返回优惠券*/
    selectedCoupon(val) {
      this.selectCouponList = []
      val.forEach((item) => {
        this.$set(item, 'num', 1)
        this.$set(item, 'couponId', item.id)

        let it = {
          ...item
        }
        this.selectCouponList.push(it)
      });
      this.couponopen = false
    },
    /**
     * 返回会员*/
    selectedMember(val) {
      this.selectMemberList = val
      this.memberopen = false
      console.log("selectMemberList:" + JSON.stringify(this.selectMemberList))
    },
  }
};
</script>
